package com.guardian.communication.nettry;

import com.guardian.communication.CommunicationService;
import com.guardian.communication.nettry.handler.MessageServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * netty 通讯服务对象 ，基于netty组件的通讯处理服务
 * @author: huwei
 * @date: 2019/10/10 16:31
 * @version: 1.0.0
 */
public class NettyCommunicationService implements CommunicationService {

    @Override
    public void syncStartup(int port) {
        //配置服务端的NIO线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .childHandler(new ChannelInitializer<Channel>() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            ChannelPipeline pipeline = channel.pipeline();
                            //入栈消息编码器，将bytes 转为 string
                            pipeline.addLast(new StringEncoder());
                            //出栈消息解码器，将string 转为 bytes
                            pipeline.addLast(new StringDecoder());
                            //入栈消息消费对象
                            pipeline.addLast(new MessageServerHandler());
                        }
                    });

            //绑定端口，同步等待成功
            ChannelFuture f = b.bind(port).sync();
            //等待服务端监听端口关闭
            f.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("通讯器启动失败，系统核心功能缺失，退出系统");
            System.exit(0);
        } finally {
            // 优雅退出，释放线程资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
